import Bridge from './core/bridge';
import { setGlobalCssVar, switchTheme, initTheme } from './utils/tools';
import EventBus from './utils/event-bus';

class AiwSDK {
  constructor(options = {}) {
    this.options = options;
    this.env = 'production';
    this._agent = null;
    this.events = new EventBus();
    this.isReady = false;
    this.login = null;
    this.request = null;
    this.bridge = Bridge;
    this.theme = 'light';
    this.init();
  }
  get agent () {
    return this._agent;
  }
  init(options = {}) {
    if (this.isReady) {
      return;
    }

    this.bridge.init();

    this.bridge.once('agent.init', ({ status, data, message }) => {
      if (status === 'SUCCEEDED') {
        this._agent = data.agent;
        this.env = data.env;
        this.bridge.setAgentId(data.agent.cid);
        this.bridge.setToken(data.token);
        if (data.theme === 'light' || data.theme === 'dark') {
          this.theme = data.theme;
          switchTheme(data.theme);
        }
        if (data.cssVar && typeof data.cssVar === 'object') {
          Object.keys(data.cssVar).forEach((key) => {
            setGlobalCssVar(key, data.cssVar[key]);
          })
        }
        // console.log('[AiwAgentSDK] Config Init Success', data);
      } else if (message) {
        console.warn(message);
      }
    });
    this.bridge.send('agent.init', {}, { source: 'aiw-agent-sdk' });
    this.bridge.receive('workspace.update', ({ status, data, message }) => {

    })
    this.isReady = true;
    this.events.emit('agent:ready');
    console.log('[AiwAgentSDK] Initialized !', options);
  }
  destroy() {
    console.log('[AiwAgentSDK] Destroyed');
    this.bridge.destroy();
    this.events.emit('agent:destroy');
  }
  send() {

  }
  toggleTheme(themeName) {
    let theme = null;
    if (!themeName) {
      theme = this.theme === 'light' ? 'dark' : 'light';
    } else {
      theme = themeName;
    }
    switchTheme(theme);
    this.theme = theme;
    this.bridge.send('setTheme', { theme });
  }
  openContextMenu({ e, menuItems, data, options }) {
    this.bridge.send('openContextMenu', { e, menuItems, data, options });
  }
  closeContextMenu() {
    this.bridge.send('closeContextMenu');
  }
}

const aiw = new AiwSDK();

const initAfterDomReady = () => {
  initTheme();
}

// 自动挂载到 window 以供 script 引入
if (typeof window !== 'undefined') {
  if (document.readyState === 'complete') {
    // DOM 加载完毕，资源（图片/iframe）未加载完
    // console.log('[AiwAgentSDK] DOM complete', aiw);
  } else if (document.readyState === 'interactive') {
    // 所有资源，包括图片、iframe 加载完成
    // console.log('[AiwAgentSDK] DOM interactive', aiw);
    initAfterDomReady();
  } else {
    window.addEventListener('DOMContentLoaded', async () => {
      // DOM 加载完毕
      // console.log('[AiwAgentSDK] DOM ContentLoaded', aiw);
    });
  }
  window.aiw = aiw;
}

export default aiw;